package org.jeecg.trace.controller;

import com.baomidou.dynamic.datasource.annotation.DS;
import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;

import org.jeecg.common.util.oConvertUtils;
import org.jeecg.trace.entity.MesPackItem;
import org.jeecg.trace.entity.MesLotStatus;
import org.jeecg.trace.service.IMesLotStatusService;
import org.jeecg.trace.service.IMesPackItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 产品批次表
 * @Author: shaolong
 * @Date: 2022-11-16
 * @Version: V1.0
 */
@Api(tags = "产品批次表")
@RestController
@RequestMapping("/trace/mesLotStatus")
@Slf4j
public class MesLotStatusController extends JeecgController<MesLotStatus, IMesLotStatusService> {

	@Autowired
	private IMesLotStatusService mesLotStatusService;

	@Autowired
	private IMesPackItemService mesPackItemService;
	


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询  erp
	 *
	 * @param mesLotStatus
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "产品批次表-分页列表查询")
	@ApiOperation(value = "产品批次表-分页列表查询", notes = "产品批次表-分页列表查询")
	@GetMapping(value = "/list")
	@DS("history")
	public Result<IPage<MesLotStatus>> queryPageList(MesLotStatus mesLotStatus,
													 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
													 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
													 HttpServletRequest req) {
//		QueryWrapper<MesLotStatus> queryWrapper = QueryGenerator.initQueryWrapper(mesLotStatus, req.getParameterMap());
		Page<MesLotStatus> page = new Page<MesLotStatus>(pageNo, pageSize);
		IPage<MesLotStatus> pageList = mesLotStatusService.pageList(page, mesLotStatus);
		pageList.getRecords().forEach(item->{
			item.setRecId(item.getLine()+'*'+item.getLotno());
		});
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 *
	 * @param mesLotStatus
	 * @return
	 */
	@AutoLog(value = "产品批次表-添加")
	@ApiOperation(value = "产品批次表-添加", notes = "产品批次表-添加")
	@PostMapping(value = "/add")
	@DS("history")
	public Result<String> add(@RequestBody MesLotStatus mesLotStatus) {
		mesLotStatusService.save(mesLotStatus);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param mesLotStatus
	 * @return
	 */
	@AutoLog(value = "产品批次表-编辑")
	@ApiOperation(value = "产品批次表-编辑", notes = "产品批次表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
	@DS("history")
	public Result<String> edit(@RequestBody MesLotStatus mesLotStatus) {
		mesLotStatusService.edit(mesLotStatus);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param map
	 * @return
	 */
	@AutoLog(value = "产品批次表-通过id删除")
	@ApiOperation(value = "产品批次表-通过id删除", notes = "产品批次表-通过id删除")
	@DeleteMapping(value = "/delete")
	@DS("history")
	public Result<String> delete(@RequestParam Map<String, Object> map) {
		mesLotStatusService.delMain((String) map.get(""));
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "产品批次表-批量删除")
	@ApiOperation(value = "产品批次表-批量删除", notes = "产品批次表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@DS("history")
	public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		this.mesLotStatusService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 *
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	@DS("history")
	public ModelAndView exportXls(HttpServletRequest request, MesLotStatus mesLotStatus) {
		return super.exportXls(request, mesLotStatus, MesLotStatus.class, "产品批次表");
	}

	/**
	 * 导入
	 *
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@DS("history")
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, MesLotStatus.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/


	/*--------------------------------子表处理-包装子表-begin----------------------------------------------*/

	/**
	 * 通过主表ID查询1
	 *
	 * @return
	 */
	//@AutoLog(value = "包装子表-通过主表ID查询")
	@ApiOperation(value = "包装子表-通过主表ID查询", notes = "包装子表-通过主表ID查询")
	@GetMapping(value = "/listMesPackItemByMainId")
	@DS("history")
	public Result<IPage<MesPackItem>> listMesPackItemByMainId(MesPackItem mesPackItem,
															  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
															  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
															  HttpServletRequest req) {
		QueryWrapper<MesPackItem> queryWrapper = QueryGenerator.initQueryWrapper(mesPackItem, req.getParameterMap());
		Page<MesPackItem> page = new Page<MesPackItem>(pageNo, pageSize);
		IPage<MesPackItem> pageList = mesPackItemService.pageList(page, mesPackItem);
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 *
	 * @param mesPackItem
	 * @return
	 */
	@AutoLog(value = "包装子表-添加")
	@ApiOperation(value = "包装子表-添加", notes = "包装子表-添加")
	@PostMapping(value = "/addMesPackItem")
	@DS("history")
	public Result<String> addMesPackItem(@RequestBody MesPackItem mesPackItem) {
		mesPackItemService.save(mesPackItem);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param mesPackItem
	 * @return
	 */
	@AutoLog(value = "包装子表-编辑")
	@ApiOperation(value = "包装子表-编辑", notes = "包装子表-编辑")
	@RequestMapping(value = "/editMesPackItem", method = {RequestMethod.PUT, RequestMethod.POST})
	@DS("history")
	public Result<String> editMesPackItem(@RequestBody MesPackItem mesPackItem) {
		mesPackItemService.edit(mesPackItem);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "包装子表-通过id删除")
	@ApiOperation(value = "包装子表-通过id删除", notes = "包装子表-通过id删除")
	@DeleteMapping(value = "/deleteMesPackItem")
	@DS("history")
	public Result<String> deleteMesPackItem(@RequestParam(name = "id", required = true) String id) {
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("", hashMap.get(""));
		mesPackItemService.removeByMap(hashMap);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "包装子表-批量删除")
	@ApiOperation(value = "包装子表-批量删除", notes = "包装子表-批量删除")
	@DeleteMapping(value = "/deleteBatchMesPackItem")
	@DS("history")
	public Result<String> deleteBatchMesPackItem(@RequestParam(name = "ids", required = true) String ids) {
		this.mesPackItemService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 *
	 * @return
	 */
	@RequestMapping(value = "/exportMesPackItem")
	@DS("history")
	public ModelAndView exportMesPackItem(HttpServletRequest request, MesPackItem mesPackItem) {
		// Step.1 组装查询条件
		QueryWrapper<MesPackItem> queryWrapper = QueryGenerator.initQueryWrapper(mesPackItem, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<MesPackItem> pageList = mesPackItemService.list(queryWrapper);
		List<MesPackItem> exportList = null;

		// 过滤选中数据2
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getPackId())).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//此处设置的filename无效,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.FILE_NAME, "包装子表");
		mv.addObject(NormalExcelConstants.CLASS, MesPackItem.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("包装子表报表", "导出人:" + sysUser.getRealname(), "包装子表"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 *
	 * @return
	 */
	@RequestMapping(value = "/importMesPackItem/{mainId}")
	@DS("history")
	public Result<?> importMesPackItem(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<MesPackItem> list = ExcelImportUtil.importExcel(file.getInputStream(), MesPackItem.class, params);
				for (MesPackItem temp : list) {
					temp.setPackId(mainId);
				}
				long start = System.currentTimeMillis();
				mesPackItemService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.OK("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-包装子表-end----------------------------------------------*/


}
